<template>
  <el-tooltip :content="tooltipText" placement="top">
    <el-button
      :icon="copyIcon"
      size="small"
      type="primary"
      :class="['copy-btn', { 'copy-success': copied }]"
      @click="handleCopy"
      plain
      circle
    />
  </el-tooltip>
</template>

<script setup>
import { ref, computed } from "vue"
import { CopyDocument, Check } from "@element-plus/icons-vue"
import { ElMessage } from "element-plus"

const props = defineProps({
  text: {
    type: String,
    required: true
  },
  successMessage: {
    type: String,
    default: "复制成功"
  }
})

const copied = ref(false)

const copyIcon = computed(() => {
  return copied.value ? Check : CopyDocument
})

const tooltipText = computed(() => {
  return copied.value ? "已复制" : "点击复制"
})

const handleCopy = async () => {
  try {
    await navigator.clipboard.writeText(props.text)
    copied.value = true
    ElMessage.success(props.successMessage)

    // 2秒后重置状态
    setTimeout(() => {
      copied.value = false
    }, 2000)
  } catch (err) {
    // 降级方案：使用传统方法复制
    const textArea = document.createElement("textarea")
    textArea.value = props.text
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand("copy")
    document.body.removeChild(textArea)

    copied.value = true
    ElMessage.success(props.successMessage)

    setTimeout(() => {
      copied.value = false
    }, 2000)
  }
}
</script>

<style lang="scss" scoped>
.copy-btn {
  margin-left: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: scale(1.1);
  }

  &.copy-success {
    --el-button-text-color: #67c23a;
    --el-button-border-color: #67c23a;
    --el-button-hover-text-color: #67c23a;
    --el-button-hover-border-color: #67c23a;
  }
}
</style>
